package com.mobile.web.organization;
import com.mobile.service.inter.system.OrganizationService;
import com.mobile.util.AppUtil;
import com.mobile.web.base.BaseController;
import com.mobile.web.config.util.Jurisdiction;
import com.mobile.util.Const;
import com.mobile.util.MessageUtil;
import com.mobile.util.PageData;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织管理模块API接口
 */
@RestController
@RequestMapping("/organization")
public class OrganizationController extends BaseController {

    @Autowired
    private OrganizationService organizationService;

    /**
     * 获取组织列表
     * @return
     */
    @PostMapping("/getOrganizationList")
    @ResponseBody
    public Object getOrganizationTreeList(){
        //获取request参数
        Map<String, Object> map = new HashMap<>();
        try {
            //调用查询
            List<PageData> organizationList = organizationService.getOrganizationTreeList(null);
            //list转为map 减少循环次数
            Map<String,List<PageData>> treeMap=organizationList.stream().collect(Collectors.groupingBy(x->x.get("parentId").toString()));
            //获取最上级组织(单位)
            List<PageData> organizationTreeList = organizationList.stream().filter(x -> "0".equals(x.get("parentId").toString())).collect(Collectors.toList());
            organizationTreeList = organizationTreeList(organizationTreeList, treeMap);
            map.put("data", organizationTreeList);
            map.put("QX", Jurisdiction.getHC(this.getUserCode(),"orginfo"));
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    /**
     * 获取组织列表
     * @return
     */
    @PostMapping("/getOrganizationListTree")
    @ResponseBody
    //@RequiresPermissions("orginfo:read:1")
    public Object getOrganizationListTree(){
        //获取request参数
        Map<String, Object> map = new HashMap<>();
        try {
            PageData pd = new PageData();
            String roleCode = this.getUser().getString("role_code");
            //非管理员和总经理 过滤组织树
            if(!Const.ROLE_CODE_ADMIN.equals(roleCode) && !Const.ROLE_CODE_MANAGER.equals(roleCode)) {
                String organizationId = this.getUser().get("organization_id").toString();
                List<String> orgs = new ArrayList<>();
                orgs = organizationService.getAllParentId(organizationId, orgs);
                orgs = organizationService.getAllLowId(organizationId, orgs);
                StringBuffer str = new StringBuffer();
                for (String s : orgs) {
                    str.append(s);
                    str.append(",");
                }

                pd.put("organizationIds", str.substring(0, str.length() - 1));
            }

            //调用查询
            List<PageData> organizationList = organizationService.getOrganizationTreeList(pd);

            //list转为map 减少循环次数
            Map<String,List<PageData>> treeMap=organizationList.stream().collect(Collectors.groupingBy(x->x.get("parentId").toString()));
            //获取最上级组织(单位)
            List<PageData> organizationTreeList = organizationList.stream().filter(x -> "0".equals(x.get("parentId").toString())).collect(Collectors.toList());
            organizationTreeList = organizationTreeList(organizationTreeList, treeMap);
            map.put("data", organizationTreeList);
            map.put("QX", Jurisdiction.getHC(this.getUserCode(),"orginfo"));
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }
    /**
     * 获取组织信息
     * @return
     */
    @PostMapping("/getOrganization")
    @ResponseBody
    //@RequiresPermissions("orginfo:read:1")
    public Object getOrganization(){
        //获取request参数
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<>();
        try {
            //调用查询
            List<PageData> department = organizationService.getOrganizationBySerch(pd);
            if(department.size() == 0){
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
                return AppUtil.returnObject(pd, map);
            }
            map.put("data", department.get(0));
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 新增组织信息
     *
     * @return
     */
    @PostMapping("/insertOrganization")
    //@RequiresPermissions("orginfo:add:1")
    public Object insertOrganization() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<>();
        // 保存权限信息
        try {
            int i = organizationService.insertOrganization(pd);
            //实现层 传值-1代表名称重复
            if (-1 == i) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0004","组织名称"));
            } else if (-2 ==i) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0216"));
            } else {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
            }
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(pd, map);
    }

    /**
     * 修改组织信息
     *
     * @return
     */
    @PostMapping("/editOrganization")
    //@RequiresPermissions("orginfo:edit:1")
    public Object editOrganization() {
        PageData pd = this.getPageData();
        PageData data = new PageData();
        Map<String, Object> map = new HashMap<>();
        // 保存权限信息
        try {
            data.put("organizationId",pd.get("organizationId"));
            List<PageData>  pageData = organizationService.getOrganizationBySerch(data);
            // 判断删除
            if (pageData.size() == 0){
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
                return AppUtil.returnObject(map);
            }
            int i = organizationService.updateDepartment(pd);
            //实现层 传值-1代表名称重复
            if (-1 == i) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0004","部门名称"));
            }else if (-2 ==i) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0216"));
            } else{
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
            }
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(pd, map);
    }
    /**
     * 根据id删除组织
     *
     * @return
     */
    @PostMapping("/removeOrganization")
    //@RequiresPermissions("orginfo:delete:1")
    public Object removeOrganization() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<>();

        try {
            String[] id = pd.getString("organizationId").split(",");
            organizationService.deleteOrganizationByBatch(id);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(pd, map);
    }
    //树形结构递归获取组织机构列表
    List<PageData> organizationTreeList(List<PageData> organizationTreeList,Map<String,List<PageData>> treeMap) {
        organizationTreeList.forEach(pd->{
            List<PageData> list = Optional.ofNullable(treeMap.get(pd.get("organizationId").toString())).orElse(new ArrayList<>());
            list = organizationTreeList(list, treeMap);
            pd.put("children", list);
        });
        return organizationTreeList;
    }
}
